<template>
	<view class="page-container">
		<!-- 日历组件 -->
		<view class="calendar-container">
			<attend-calendar :lateddates="['2024-08-29']" @on-click="handlerChangeDate"></attend-calendar>
		</view>

		<!-- 预约记录区域 -->
		<view class="reserve-section">
			<view class="section-header">
				<up-icon name="list" color="#6FD719" size="20"></up-icon>
				<text class="section-title">预约记录</text>
				<text class="date-info">{{formatDate(data.currnetDate)}}</text>
			</view>

			<view class="reserve-content">
				<template v-if="data.reserveList?.length > 0">
					<view class="reserve-item" v-for="(item, index) in data.reserveList" :key="index" @click="handlerShowPopup(item.studentId)">
						<view class="item-left">
							<view class="image-wrapper">
								<up-image
									class="item-image"
									width="100rpx"
									height="100rpx"
									radius="16"
									:src="config.baseUrl+item?.pics"
									mode="aspectFill"
								>
									<template #error>
										<view class="image-error">
											<up-icon name="photo" color="#ddd" size="20"></up-icon>
										</view>
									</template>
								</up-image>
							</view>
						</view>
						<view class="item-content">
							<view class="student-info">
								<view class="student-name">{{item.studentName}}</view>
								<up-tag
									text="已预约"
									type="success"
									size="mini"
									bgColor="rgba(111, 215, 25, 0.1)"
									color="#6FD719"
									borderColor="transparent"
								></up-tag>
							</view>
							<view class="combo-info">
								<text class="combo-text">{{ item.comboName }}</text>
							</view>
							<view class="dish-info">
								<up-icon name="list" color="#999" size="12"></up-icon>
								<text class="dish-text">{{ item.dishName }}</text>
							</view>
						</view>
						<view class="item-action">
							<up-icon name="edit-pen" color="#6FD719" size="16"></up-icon>
							<text class="action-text">变更</text>
						</view>
					</view>
				</template>

				<template v-else>
					<view class="empty-container">
						<up-empty
							mode="list"
							text="当日暂无预约记录"
							textColor="#999"
							iconColor="#ddd"
						></up-empty>
						<view class="empty-tip">
							<text>请选择其他日期查看预约记录</text>
						</view>
					</view>
				</template>
			</view>
		</view>

		<!-- 变更套餐弹窗 -->
		<up-popup :show="data.popupShow" mode="bottom" round="30" @close="()=>data.popupShow = false" closeable>
			<view class="popup-container">
				<view class="popup-header">
					<view class="popup-title">
						<up-icon name="edit-pen" color="#6FD719" size="20"></up-icon>
						<text>变更套餐</text>
					</view>
				</view>

				<view class="popup-content">
					<!-- 周末提示 -->
					<view class="weekend-notice" v-if="isWeekend()">
						<up-icon name="info-circle" color="#FF9800" size="16"></up-icon>
						<text>周末不可更改预约</text>
					</view>

					<!-- 过期提示 -->
					<view class="expired-notice" v-else-if="isPastDate()">
						<up-icon name="info-circle" color="#FF6B6B" size="16"></up-icon>
						<text>过期日期不可更改预约</text>
					</view>

					<!-- 调试信息 -->
					<!-- #ifdef MP-WEIXIN -->
					<view class="debug-info" v-if="false">
						<text>套餐数量: {{ data.comboList?.length || 0 }}</text>
						<text>选中ID: {{ data.selectId }}</text>
					</view>
					<!-- #endif -->
					<!-- #ifndef MP-WEIXIN -->
					<view class="debug-info" v-if="process.env && process.env.NODE_ENV === 'development'">
						<text>套餐数量: {{ data.comboList?.length || 0 }}</text>
						<text>选中ID: {{ data.selectId }}</text>
					</view>
					<!-- #endif -->

					<template v-if="data.comboList && data.comboList.length > 0">
						<up-radio-group v-model="data.selectId" placement="row">
							<template v-for="(item, index) in data.comboList" :key="item.id || index">
								<view class="combo-option" :class="{ 'combo-disabled': isDisabled() }">
									<view class="radio-wrapper">
										<up-radio
											active-color="#6FD719"
											:name="item.id"
											:disabled="isDisabled()"
										></up-radio>
									</view>
									<view class="combo-item-wrapper">
										<ComboItem :item="item"></ComboItem>
									</view>
								</view>
							</template>
						</up-radio-group>
					</template>

					<template v-else>
						<view class="empty-combo">
							<up-empty
								mode="search"
								text="暂无可选套餐"
								textColor="#999"
								iconColor="#ddd"
							></up-empty>
						</view>
					</template>
				</view>

				<view class="popup-actions">
					<up-button
						type="primary"
						size="large"
						:disabled="isDisabled()"
						@click="handlerCreateResrve"
						customStyle="background: linear-gradient(135deg, #6FD719 0%, #5BC016 100%); border: none; border-radius: 25rpx; box-shadow: 0 4px 16px rgba(111, 215, 25, 0.3);"
					>
						<up-icon name="checkmark" color="#fff" size="16" style="margin-right: 8rpx;"></up-icon>
						<text style="color: #fff; font-weight: 600;">确认变更</text>
					</up-button>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import AttendCalendar from '../../components/attend-calendar/attend-calendar.vue';
	import ComboItem from '../../components/ComboItem/index.vue';
	import {
		config
	} from '../../config/index.js'
	import {
		reactive
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		listHistoryResrve,getSelectComboListByDate,createResrve
	} from '../../api/combo.js'
	const data = reactive({
		reserveList: [],
		popupShow: false,
		selectId: null,
		comboList: [],
		currnetDate: null,
		studentId: null
	})
	import dayjs from 'dayjs'

	onLoad(() => {
		data.currnetDate = dayjs().format('YYYY-MM-DD')
		getDataList()
	})

	const getDataList = async () => {
		const userInfo = uni.getStorageSync('userInfo')
		data.reserveList = await listHistoryResrve({
			parentId: userInfo.id,
			date: data.currnetDate
		});
	}

	const handlerChangeDate = (date) => {
		data.currnetDate  = dayjs(date).format('YYYY-MM-DD')
		getDataList()
	}

	// 检查是否是周末
	const isWeekend = () => {
		const today = new Date();
		const todayDayOfWeek = today.getDay(); // 0 表示周日，6 表示周六
		return todayDayOfWeek === 6 || todayDayOfWeek === 0;
	}

	// 检查是否是过期日期
	const isPastDate = () => {
		return dayjs().isAfter(dayjs(data.currnetDate));
	}

	// 检查是否禁用（周末或过期日期）
	const isDisabled = () => {
		return isWeekend() || isPastDate();
	}
	
	const handlerShowPopup = async (studentId)=>{
		try {
			data.studentId = studentId;

			// 获取套餐列表和学生选择信息（一次性获取）
			console.log('获取套餐列表和选择信息，日期:', data.currnetDate, '学生ID:', studentId);
			const result = await getSelectComboListByDate(data.currnetDate, studentId);
			console.log('返回的完整数据:', result);

			// 处理返回的数据结构
			if (result && typeof result === 'object') {
				// 设置套餐列表
				data.comboList = result.comboList || [];
				console.log('套餐列表:', data.comboList);

				// 设置学生已选择的套餐ID
				data.selectId = result.selectedComboId || null;
				console.log('学生已选择的套餐ID:', data.selectId);
			} else {
				// 兼容旧的数据结构（直接返回套餐列表）
				data.comboList = Array.isArray(result) ? result : [];
				data.selectId = null;
				console.log('⚠️ 使用兼容模式，套餐数量:', data.comboList.length);
			}

			// 显示弹窗
			data.popupShow = true;
		} catch (error) {
			console.error('获取数据失败:', error);
			uni.showToast({
				title: '获取数据失败',
				icon: 'error'
			});
		}
	}
	
	const handlerCreateResrve = async ()=>{
		try {
			if (!data.selectId) {
				uni.showToast({
					title: '请选择套餐',
					icon: 'error'
				});
				return;
			}

			console.log('创建预约，学生ID:', data.studentId, '套餐ID:', data.selectId);
			await createResrve({studentId:data.studentId,comboIdList:[data.selectId]});

			uni.showToast({
				title: '变更成功',
				icon: 'success'
			});

			data.popupShow = false;

			// 刷新预约列表
			await getDataList();
		} catch (error) {
			console.error('变更失败:', error);
			uni.showToast({
				title: '变更失败',
				icon: 'error'
			});
		}
	}

	// 格式化日期显示
	const formatDate = (date) => {
		if (!date) return '';
		const d = dayjs(date);
		const today = dayjs();
		const tomorrow = dayjs().add(1, 'day');
		const yesterday = dayjs().subtract(1, 'day');

		if (d.isSame(today, 'day')) {
			return '今天 ' + d.format('MM-DD');
		} else if (d.isSame(tomorrow, 'day')) {
			return '明天 ' + d.format('MM-DD');
		} else if (d.isSame(yesterday, 'day')) {
			return '昨天 ' + d.format('MM-DD');
		} else {
			return d.format('MM月DD日');
		}
	}
</script>

<style lang="scss" scoped>
	.page-container {
		background: linear-gradient(180deg, #F8FAFB 0%, #FFFFFF 100%);
		min-height: 100vh;
	}

	/* 日历容器 */
	.calendar-container {
		position: relative;
		z-index: 1;
	}

	/* 预约记录区域 */
	.reserve-section {
		background: linear-gradient(135deg, #FFFFFF 0%, #FAFBFC 100%);
		border-radius: 30rpx 30rpx 0 0;
		margin-top: -30rpx;
		padding: 40rpx 30rpx;
		min-height: 500rpx;
		box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.05);
		position: relative;
		z-index: 2;
	}

	.section-header {
		display: flex;
		align-items: center;
		gap: 12rpx;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #F5F7FA;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		flex: 1;
	}

	.date-info {
		font-size: 26rpx;
		color: #6FD719;
		background: rgba(111, 215, 25, 0.1);
		padding: 8rpx 16rpx;
		border-radius: 16rpx;
		font-weight: 500;
	}

	/* 预约记录列表 */
	.reserve-content {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.reserve-item {
		background: linear-gradient(135deg, #FFFFFF 0%, #FAFBFC 100%);
		border-radius: 25rpx;
		padding: 30rpx;
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
		border: 1px solid rgba(255, 255, 255, 0.8);
		display: flex;
		align-items: center;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
		}
	}

	.item-left {
		margin-right: 24rpx;
	}

	.image-wrapper {
		position: relative;
	}

	.item-image {
		border-radius: 16rpx;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
	}

	.image-error {
		width: 100rpx;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #F5F7FA;
		border-radius: 16rpx;
	}

	.item-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.student-info {
		display: flex;
		align-items: center;
		gap: 12rpx;
	}

	.student-name {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.combo-info,
	.dish-info {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.combo-text {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.dish-text {
		font-size: 24rpx;
		color: #666;
	}

	.item-action {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 8rpx;
		padding: 12rpx;
		border-radius: 16rpx;
		background: rgba(111, 215, 25, 0.1);
		border: 1px solid rgba(111, 215, 25, 0.2);
	}

	.action-text {
		font-size: 24rpx;
		color: #6FD719;
		font-weight: 500;
	}

	/* 空状态 */
	.empty-container {
		padding: 80rpx 30rpx;
		text-align: center;
	}

	.empty-tip {
		margin-top: 20rpx;

		text {
			font-size: 26rpx;
			color: #999;
		}
	}

	/* 弹窗样式 */
	.popup-container {
		padding: 40rpx 30rpx;
		max-height: 80vh;
		overflow-y: auto;
	}

	.popup-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #F5F7FA;
	}

	.popup-title {
		display: flex;
		align-items: center;
		gap: 12rpx;

		text {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}
	}

	.popup-date {
		font-size: 26rpx;
		color: #6FD719;
		background: rgba(111, 215, 25, 0.1);
		padding: 8rpx 16rpx;
		border-radius: 16rpx;
		font-weight: 500;
	}

	.popup-content {
		margin-bottom: 40rpx;
	}

	/* 提示信息样式 */
	.weekend-notice,
	.expired-notice {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 16rpx 20rpx;
		margin-bottom: 20rpx;
		border-radius: 12rpx;
		font-size: 26rpx;
	}

	.weekend-notice {
		background: rgba(255, 152, 0, 0.1);
		color: #FF9800;
		border: 1rpx solid rgba(255, 152, 0, 0.2);
	}

	.expired-notice {
		background: rgba(255, 107, 107, 0.1);
		color: #FF6B6B;
		border: 1rpx solid rgba(255, 107, 107, 0.2);
	}

	.combo-option {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		padding: 20rpx;
		border-radius: 20rpx;
		border: 2rpx solid transparent;
		transition: all 0.3s ease;

		&.combo-disabled {
			opacity: 0.5;
			pointer-events: none;
		}
	}

	.radio-wrapper {
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.combo-item-wrapper {
		flex: 1;
	}

	.popup-actions {
		padding-top: 20rpx;
		border-top: 2rpx solid #F5F7FA;
	}

	/* 调试信息样式 */
	.debug-info {
		background: #f0f0f0;
		padding: 20rpx;
		border-radius: 10rpx;
		margin-bottom: 20rpx;

		text {
			display: block;
			font-size: 24rpx;
			color: #666;
			margin-bottom: 8rpx;
		}
	}

	/* 空状态样式 */
	.empty-combo {
		padding: 60rpx 30rpx;
		text-align: center;
	}

	/* 动画效果 */
	.reserve-item {
		animation: slideInUp 0.4s ease-out;
	}

	@keyframes slideInUp {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
</style>